package crond

import (
	"advertising/config/mysql"
	"advertising/internal/app/grpc/client"
	"advertising/internal/app/grpc/protoc/devicec"
	"advertising/internal/app/web/service"
	"advertising/internal/dao"
	"advertising/internal/models"
	"context"
	"strconv"
	"strings"

	"192.168.1.75/go-pkg/logx"
)

func PublishScheduleChangeStatus() error {
	ctx := context.Background()
	db := mysql.NewDB()

	// 已过期的计划处理
	{
		ExpiredScheduleIDs, _ := dao.PublishSchedule{}.ExpiredSchedule(ctx, db)
		if len(ExpiredScheduleIDs) > 0 {
			for _, v := range ExpiredScheduleIDs {
				service.PublishSchedule{}.End(ctx, db, "", v)
			}
		}
	}
	// 时间已到的计划改为投放中
	{
		timeToPublishScheduleIDs, _ := dao.PublishSchedule{}.TimeToPublishSchedule(ctx, db)
		var PublishScheduleDeviceList []*models.PublishScheduleDevice
		for _, ID := range timeToPublishScheduleIDs {
			// 编辑投放计划状态
			dao.PublishSchedule{}.ChangeSatatus(ctx, db, "", ID, []int8{}, 3)

			// 获取计划相关的设备【true 不包含待删除的设备】
			ScheduleDeviceList, _, _ := dao.PublishScheduleDevice{}.List(ctx, db, "", ID, "", 0, 0, 0, true, 0, 0)
			PublishScheduleDeviceList = append(PublishScheduleDeviceList, ScheduleDeviceList...)
		}
		var deviceList = []struct {
			RobotName    string `json:"robot_name"`
			TerminalType int    `json:"terminal_type"`
		}{}
		for _, v := range PublishScheduleDeviceList {
			deviceList = append(deviceList, struct {
				RobotName    string `json:"robot_name"`
				TerminalType int    `json:"terminal_type"`
			}{v.RobotName, v.TerminalType})
		}
		if len(deviceList) > 0 {
			var devices string
			for _, v := range deviceList {
				devices += "," + v.RobotName + "_" + strconv.Itoa(v.TerminalType)
			}
			devices = strings.TrimPrefix(devices, ",")
			// 提醒设备后台重新获取广告
			deviceAdminClient, clientErr := client.GetDeviceAdminClient()
			if clientErr != nil {
				logx.Error(ctx, "connnect error", logx.Any("error", "device_admin client connect error"))
				return nil
			}

			var params devicec.NoticePublishScheduleChangeReq
			params.Devices = devices
			deviceAdminClient.NoticePublishScheduleChange(ctx, &params)
		}
	}
	return nil
}
